import axios, { 
    AxiosInstance,
    AxiosResponse,
    CreateAxiosDefaults, 
    InternalAxiosRequestConfig,
    AxiosError
 } from "axios";
import { get } from "./session";
import router from "../router";

class Request{
    private instance:AxiosInstance// 实例
    constructor(config:CreateAxiosDefaults){
        this.instance=axios.create(config)
        this.beforeRequest()
        this.beforeResponse()
    }

    // 拦截
   private beforeRequest(){
        this
        .instance
        .interceptors
        .request
        .use((req:InternalAxiosRequestConfig)=>{
            // 请求头携带token 令牌 
            let token:string=get("token") as string
            req.headers.Authorization=token
            return req
        })
    }

   private beforeResponse(){
        this.instance.interceptors.response.use((res:AxiosResponse)=>{
            return res.data
        },(e:AxiosError)=>{
            console.log(e);
            if(e.status==401||e.status==402){
                router.replace("/login")
            }
           return e
        })
    }

    // 请求方式
    get<T>(url:string,params={}):Promise<T>{
        return this.instance({
            url,
            params,
            method:'get',
           
        })
    }
    download<T>(url:string,params={}):Promise<T>{// 下载流文件
        return this.instance({
            url,
            params,
            method:'get',
            responseType:"blob"
        })
    }
    post<T>(url:string,data={}):Promise<T>{
        return this.instance({
            url,
            data,
            method:'post'
        })
    }
    delete<T>(url:string,params={}):Promise<T>{
        return this.instance({
            url,
            params,
            method:'delete'
        })
    }
    put<T>(url:string,data={}):Promise<T>{
        return this.instance({
            url,
            data,
            method:'put'
        })
    }
}


// function fn<T>(x:T):T{
//     return x
// }

export default Request